import dbHelper from "./DbHelper"
import relationalStore from '@ohos.data.relationalStore';
import ValuesBucket from '@ohos.data.ValuesBucket';
import AdvertItem from '../model/AdvertItem';
import ArrayList from '@ohos.util.ArrayList';

const COLUMNS = ["id", "title", "img", "url", "expireTime", "base64Str"]

export default class AdvertDao {
  private tableName = "advert"

  addAdvert(valuesBucket: AdvertItem) {
    console.info("ValuesBucket:" + valuesBucket.title)
    // var isnertData ={
    //   "id":valuesBucket.id,
    //   "title":valuesBucket.title,
    //   "img":valuesBucket.img,
    //   "url":valuesBucket.url,
    //   "expireTime":valuesBucket.expireTime,
    //   "base64Str":"data:image/png;base64,"+valuesBucket.base64Str
    // }
    let predicates = new relationalStore.RdbPredicates(this.tableName)
    predicates.equalTo("id", valuesBucket.id)
    dbHelper.query<ArrayList<AdvertItem>>(predicates).then(result => {
      if (result.length == 0) {
        dbHelper.insert(this.tableName, {
          "id": valuesBucket.id,
          "title": valuesBucket.title,
          "img": valuesBucket.img,
          "url": valuesBucket.url,
          "expireTime": valuesBucket.expireTime,
          "base64Str": "data:image/png;base64," + valuesBucket.base64Str
        }).then(number => {
          console.info("addAdvertInsert========" + number)

        }).catch((error: string) => {
          console.info("addAdvert error========" + error)
          // console.info("addAdvert error========" + error.message)
        })
      } else {
        dbHelper.update({
          "id": valuesBucket.id,
          "title": valuesBucket.title,
          "img": valuesBucket.img,
          "url": valuesBucket.url,
          "expireTime": valuesBucket.expireTime,
          "base64Str": "data:image/png;base64," + valuesBucket.base64Str
        }, predicates).then(number => {
          console.info("addAdvertUpdate========" + number)
        }).catch((error: string) => {
          // console.info("addAdvert error========"+error.message)
          console.info("addAdvert error========" + error)
        })
      }
    }).catch((error: string) => {

    })

  }

  queryAdvertAll(): Promise<ArrayList<ArrayList<AdvertItem>>> {
    return dbHelper.query<ArrayList<AdvertItem>>(new relationalStore.RdbPredicates(this.tableName), COLUMNS)
  }
}
